
import cn.hutool.core.io.resource.ClassPathResource;
import cn.hutool.json.JSONObject;
import cn.hutool.setting.yaml.YamlUtil;
import com.yaolonga.itfc.manager.core.NetworkInterfaceHelper;
import com.yaolonga.itfc.manager.core.utils.CommandUtils;

import java.io.*;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.StandardCopyOption;
import java.util.*;

import static cn.hutool.core.net.NetUtil.getMacAddress;


public class TestParser {
    public static void main(String[] args) throws IOException {
        // System.out.println(parseWifiScanInfo());
        // system info
        //System.out.println("操作系统名称: " + System.getProperty("os.name"));
        //System.out.println("操作系统架构: " + System.getProperty("os.arch"));
        //System.out.println("操作系统版本: " + System.getProperty("os.version"));
        //System.out.println("Java版本: " + System.getProperty("java.version"));
        //System.out.println("Java供应商: " + System.getProperty("java.vendor"));
        //System.out.println("Java安装目录: " + System.getProperty("java.home"));
        System.out.println(CommandUtils.execClassPathShFileAndReturn("init.sh","99-yl-net-init.yaml", TestParser.class.getClassLoader()));
    }


    private static Map<String, Map<String, Object>> parseWifiScanInfo() {
        ClassPathResource classPathResource = new ClassPathResource("WifiScanInfo.log", TestParser.class);
        InputStreamReader inputStreamReader = new InputStreamReader(classPathResource.getStream());
        BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
        String line;
        Map<String, Map<String, Object>> bssids = new HashMap<>();
        try {
            // 是否忽略行
            boolean isHeader = true;
            HashMap<String, Object> bssid = null;
            Map<String, Map<String, Integer>> readIndexMap = new HashMap<>();
            while ((line = bufferedReader.readLine()) != null) {
//                System.out.println(line);
                if (line.trim().isEmpty()) {
                    continue;
                }
                line = line.trim();
                if (isHeader) {
                    readIndexMap = getFieldIndexes(line);
                    isHeader = false;
                    continue;
                }
                Map<String, Object> wifiInfoMap = new HashMap<>();
                wifiInfoMap.put("NAME", getFieldValue("NAME", line, readIndexMap));
                wifiInfoMap.put("SSID", getFieldValue("SSID", line, readIndexMap));
                wifiInfoMap.put("SSID-HEX", getFieldValue("SSID-HEX", line, readIndexMap));
                wifiInfoMap.put("BSSID", getFieldValue("BSSID", line, readIndexMap));
                wifiInfoMap.put("MODE", getFieldValue("MODE", line, readIndexMap));
                wifiInfoMap.put("CHAN", getFieldValue("CHAN", line, readIndexMap));
                wifiInfoMap.put("FREQ", getFieldValue("FREQ", line, readIndexMap));
                wifiInfoMap.put("RATE", getFieldValue("RATE", line, readIndexMap));
                wifiInfoMap.put("SIGNAL", getFieldValue("SIGNAL", line, readIndexMap));
                wifiInfoMap.put("BARS", getFieldValue("BARS", line, readIndexMap));
                wifiInfoMap.put("SECURITY", getFieldValue("SECURITY", line, readIndexMap));
                wifiInfoMap.put("WPA-FLAGS", getFieldValue("WPA-FLAGS", line, readIndexMap));
                wifiInfoMap.put("RSN-FLAGS", getFieldValue("RSN-FLAGS", line, readIndexMap));
                wifiInfoMap.put("DEVICE", getFieldValue("DEVICE", line, readIndexMap));
                wifiInfoMap.put("ACTIVE", getFieldValue("ACTIVE", line, readIndexMap));
                wifiInfoMap.put("IN-USE", getFieldValue("IN-USE", line, readIndexMap));
                wifiInfoMap.put("DBUS-PATH", getFieldValue("DBUS-PATH", line, readIndexMap));
                bssids.put((String) wifiInfoMap.get("BSSID"), wifiInfoMap);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return bssids;
    }


    public static String getFieldValue(String field, String input, Map<String, Map<String, Integer>> readIndexMap) {
        Map<String, Integer> scope = readIndexMap.get(field);
        if (scope != null) {
            Integer start = scope.get("start");
            Integer end = scope.get("end");
            if (end == -1) {
                return input.substring(start).trim();
            }
            return input.substring(start, end).trim();
        }
        return null;
    }


    public static Map<String, Map<String, Integer>> getFieldIndexes(String input) {
        input = input.trim();
        Map<String, Map<String, Integer>> result = new HashMap<>();
        int currentIndex = 0;
        int currentStartIndex = 0;
        int currentEndIndex = 0;
        String preField = "";
        while (currentIndex < input.length()) {
            if (isWordStartBoundary(input, currentIndex)) {
                currentStartIndex = currentIndex;
            } else if (isWordEndBoundary(input, currentIndex)) {
                currentEndIndex = currentIndex;
                String field = input.substring(currentStartIndex, currentEndIndex);
                if (!preField.isEmpty()) {
                    result.get(preField).put("end", currentStartIndex - 2);
                }

                Map<String, Integer> map = new HashMap<>();
                map.put("start", currentStartIndex);
                result.put(field, map);
                preField = field;
                System.out.println(field + ":" + currentIndex + "  start: " + currentStartIndex + " end:" + (currentStartIndex - 2));
            }
            currentIndex++;
        }

        String field = input.substring(currentStartIndex).trim();
        Map<String, Integer> map = new HashMap<>();
        map.put("start", currentStartIndex);
        map.put("end", -1);
        result.put(field, map);
        return result;
    }

    private static boolean isWordEndBoundary(String s, int index) {
        if (index == s.length() - 1) return true;
        char currentChar = s.charAt(index);
        char prevChar = s.charAt(index - 1);
        return currentChar == ' ' && prevChar != ' ';
    }

    private static boolean isWordStartBoundary(String s, int index) {
        if (index == 0) return true;
        char currentChar = s.charAt(index);
        char prevChar = s.charAt(index - 1);
        return currentChar != ' ' && prevChar == ' ';
    }

    private static void parseLinuxNetConf() throws IOException {
        String[] cmds = "nmcli dev show".split(" ");
        ProcessBuilder processBuilder = new ProcessBuilder(cmds);
        Process start = processBuilder.start();
        InputStream inputStream = start.getInputStream();

        Map<String, Map<String, Object>> netMap = getNetMap();

        if (inputStream != null) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            try {
                // 是否忽略行
                boolean ignoreLine = false;
                while ((line = bufferedReader.readLine()) != null) {
                    if (line.trim().isEmpty()) {
                        continue;
                    }

                    if (line.contains("GENERAL.DEVICE:")) {
                        System.out.println("\n");
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String value = split[1].trim();
                            Map<String, Object> info = netMap.get(value);
                            System.out.println("interfaceName：" + value);
                            if (info != null) {
                                Object ifIndex = info.get("ifIndex");
                                Object dhcp = info.get("dhcp");
                                System.out.println("ifIndex：" + ifIndex);
                                System.out.println("dhcp：" + dhcp);
                            }

                        }
                        continue;
                    }

                    if (line.contains("GENERAL.TYPE:")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String value = split[1].trim();
                            System.out.println("interfaceType：" + value);
                        }
                        continue;
                    }

                    if (line.contains("GENERAL.STATE:")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            boolean value = "100".equals(split[1]);
                            System.out.println("interfaceState：" + value);
                        }
                        continue;
                    }

                    if (line.contains("GENERAL.MTU:")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String value = split[1].trim();
                            System.out.println("interfaceMtu：" + value);
                        }
                        continue;
                    }

                    if (line.contains("GENERAL.HWADDR:")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String value = split[1].trim();
                            System.out.println("interfaceMac：" + value);
                        }
                        continue;
                    }

                    if (line.startsWith("IP4.ADDRESS")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String[] split1 = split[1].trim().split("/");
                            String value = split1[0];
                            int mask = Integer.parseInt(split1[1]);
                            System.out.println("interfaceIpv4：" + value);
                            // mask转换为ipv4
                            System.out.println("interfaceMask：" + getMaskIp(mask));
                        }
                        continue;
                    }
                    if (line.contains("IP4.GATEWAY:")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String value = split[1].trim();
                            System.out.println("interfaceGateway：" + value);
                        }
                        continue;
                    }

                    if (line.contains("IP4.DNS")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String value = split[1].trim();
                            System.out.println("interfaceDns：" + value);
                        }
                        continue;
                    }

                    if (line.contains("IP4.ROUTE")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String value = split[1].trim();

                            String[] split1 = value.split(",");

                            String s = split1[0].trim();
                            String[] split2 = s.split("=")[1].trim().split("/");
                            String target = split2[0].trim();
                            int mask = Integer.parseInt(split2[1].trim());
                            // 网络地址
                            System.out.println("interfaceRoute-target：" + target);
                            // 子网
                            System.out.println("interfaceRoute-mask：" + getMaskIp(mask));


                            // 网关
                            String s1 = split1[1].trim();
                            String[] split3 = s1.split("=");
                            String gateway = split3[1].trim();
                            System.out.println("interfaceRoute-gateway：" + gateway);

                            // 跳数
                            String s2 = split1[2].trim();
                            String[] split4 = s2.split("=");
                            String metric = split4[1].trim();
                            System.out.println("interfaceRoute-metric：" + metric);
                        }
                        continue;
                    }

                    if (line.contains("IP6.ADDRESS")) {
                        String[] split = line.split(": ");
                        if (split.length > 1) {
                            String[] split1 = split[1].trim().split("/");
                            String value = split1[0];
                            int mask = Integer.parseInt(split1[1]);
                            System.out.println("interfaceIpv6：" + value);
                            // mask转换为ipv4
                            System.out.println("interfaceMask：" + getMaskIp(mask));
                        }
                    }
                }
            } catch (IOException e) {
            }
        }
    }

    private static String getMaskIp(int mask) {
        StringBuilder maskIp = new StringBuilder();
        for (int i = 0; i < 4; i++) {
            int mask1 = mask - i * 8;
            int mask2 = Math.min(mask1, 8);
            int mask3 = 0xff << (8 - mask2);
            maskIp.append((mask3 & 0xff)).append(".");
        }
        if (maskIp.toString().endsWith(".")) {
            return maskIp.substring(0, maskIp.length() - 1);
        }
        return maskIp.toString();
    }


    private static Map<String, Map<String, Object>> getNetMap() throws IOException {
        String[] cmds = "ip -o addr show".split(" ");
        ProcessBuilder processBuilder = new ProcessBuilder(cmds);
        Process start = processBuilder.start();
        InputStream inputStream = start.getInputStream();

        HashMap<String, Map<String, Object>> res = new HashMap<>();
        if (inputStream != null) {
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
            String line;
            try {
                // 是否忽略行
                boolean ignoreLine = false;
                while ((line = bufferedReader.readLine()) != null) {
                    // 忽略ipv6
                    if (line.contains("inet6")) {
                        continue;
                    }
                    String[] split = line.split(": ");
                    if (split.length > 1) {
                        int ifIndex = Integer.parseInt(split[0].trim());
                        String[] split1 = split[1].trim().split(" ");
                        String itfc = split1[0].trim();
                        boolean dhcp = false;
                        if (line.contains("global dynamic")) {
                            dhcp = true;
                        }
                        HashMap<String, Object> stringObjectHashMap = new HashMap<>();
                        stringObjectHashMap.put("dhcp", dhcp);
                        stringObjectHashMap.put("ifIndex", ifIndex);
                        res.put(itfc, stringObjectHashMap);
                    }
                }
            } catch (IOException e) {

            }
        }

        return res;
    }
}